import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    component: () => import('@/layout/index.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘', icon: 'DataAnalysis' }
      },
      {
        path: 'log-search',
        name: 'LogSearch',
        component: () => import('@/views/LogSearch.vue'),
        meta: { title: '日志检索', icon: 'Search' }
      },
      {
        path: 'log-source',
        name: 'LogSource',
        component: () => import('@/views/LogSource.vue'),
        meta: { title: '日志采集配置', icon: 'Files' }
      },
      {
        path: 'network-log',
        name: 'NetworkLog',
        component: () => import('@/views/LogCacheMonitor.vue'),
        meta: { title: '网络日志接收', icon: 'Connection' }
      },
      {
        path: 'alarm',
        name: 'Alarm',
        component: () => import('@/views/Alarm.vue'),
        meta: { title: '告警管理', icon: 'Bell' }
      },
      {
        path: 'statistics',
        name: 'Statistics',
        component: () => import('@/views/Statistics.vue'),
        meta: { title: '统计分析', icon: 'TrendCharts' }
      },
      {
        path: 'log-test',
        name: 'LogTest',
        component: () => import('@/views/LogTest.vue'),
        meta: { title: '日志测试工具', icon: 'Operation' }
      },
      {
        path: 'system',
        name: 'System',
        component: () => import('@/views/System.vue'),
        meta: { title: '系统管理', icon: 'Setting', role: 1 }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  NProgress.start()
  
  const userStore = useUserStore()
  
  if (to.path === '/login') {
    next()
  } else {
    if (userStore.token) {
      // 角色权限检查
      if (to.meta.role && to.meta.role !== userStore.role) {
        next('/dashboard')
      } else {
        next()
      }
    } else {
      next('/login')
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router

